import type { Dispatch, SetStateAction } from 'react';
import React, { useEffect } from 'react';
import { features, useTablePipeline } from 'ali-react-table';
import { Button, Checkbox, Dropdown, message, Tooltip } from 'antd';
import type { CheckboxChangeEvent } from 'antd/es/checkbox';
import type { CheckboxValueType } from 'antd/es/checkbox/Group';
import moment from 'moment/moment';
import _ from 'lodash';

//@ts-ignore
import { TjTable } from '@/pages/ETrade/components';
//@ts-ignore
import { useTRState } from '#/utils/trHooks';
//@ts-ignore
import PLoading from '#/components/PLoading';
import { FilterOutlined } from '#/utils/antdIcons.js';

import {
  contractSourceOptions,
  operationList,
  plainOptions,
  totalColorDic,
} from '../../dictionary';
import { havePermissions, ToFixed, USER_TYPE_DIC } from '../../tool';
import type { IListType, IOptionType } from '../../type';
import { IContractSourceType, IOperationType } from '../../type';
import styles from './index.less';
import { exportXinjiangContract } from '@/pages/ETrade/ContractManagement/service';

const CheckboxGroup = Checkbox.Group;

interface IProps {
  /**
   * 是否显示量价图
   */
  visible?: boolean;
  /**
   * 展开的行对应的合约Id
   */
  contractId?: string;
  /**
   * 数据源
   */
  dataSource?: IListType[];
  /**
   * 选择参数
   */
  selectedRowKeys?: string[];
  /**
   * 改变选择参数
   */
  setSelectedRowKeys?: Dispatch<SetStateAction<string[]>>;
  /**
   * 操作权限列表
   */
  buttonPermissions?: any;
  /**
   * 点击合约分析图
   */
  showContratCharts?: (record: any) => void;
  /**
   * 编辑数据
   */
  onEdit?: (record: IListType) => void;
  /**
   * 删除数据
   */
  onDetele?: (record: IListType) => void;
  /**
   * 展示详情
   */
  onDetail?: (record: IListType) => void;
  /**
   * 数据汇总展板数据
   */
  totalData?: any;
}

const XJList = (props: IProps) => {
  const {
    totalData = [],
    visible = false,
    contractId,
    dataSource = [],
    selectedRowKeys = [],
    buttonPermissions,
    setSelectedRowKeys,
    onEdit,
    onDetail,
    onDetele,
  } = props;
  const [state, setState] = useTRState({
    indeterminate: false,
    checkAll: true,
    open: false,
    selectedKeys: plainOptions.map((t) => t.value),
    loading: false,
    data: _.cloneDeep(dataSource),
    filterKey: plainOptions.map((t) => t.value),
  });

  //全选
  const onCheckAllChange = (e: CheckboxChangeEvent) => {
    setState({
      selectedKeys: e?.target.checked ? plainOptions.map((t) => t.value) : [],
      indeterminate: false,
      checkAll: e?.target.checked,
    });
  };
  //单选
  const onCheck = (selectedKeys: CheckboxValueType[]) => {
    setState({
      selectedKeys,
      indeterminate: !!selectedKeys.length && selectedKeys.length < plainOptions.length,
      checkAll: selectedKeys.length === plainOptions.length,
    });
  };
  //菜单显隐
  const columnsVisibleChange = (flag: boolean) => {
    setState({
      open: flag,
    });
  };
  //取消
  const onCancel = () => {
    setState({
      open: false,
      selectedKeys: state.filterKey,
      indeterminate: !!state.filterKey.length && state.filterKey.length < plainOptions.length,
      checkAll: state.filterKey.length === plainOptions.length,
    });
  };
  //确定
  const onSuccess = async () => {
    const _list = _.cloneDeep(dataSource).map((i: any) => {
      const _child: any = [];
      if (i.children instanceof Array) {
        i.children.forEach((n: any) => {
          if (state.selectedKeys.includes(n.tag)) {
            _child.push(n);
          }
        });
      }
      i.children = _child;
      return i;
    });
    setState({
      loading: true,
    });
    setState({
      loading: false,
      open: false,
      filterKey: state.selectedKeys,
      data: _list,
    });
  };
  const renderColumns = () => {
    return (
      <div className={styles.columns_container}>
        <div className={styles.columns_container_header}>
          <Checkbox
            indeterminate={state.indeterminate}
            onChange={onCheckAllChange}
            checked={state.checkAll}
          >
            全选
          </Checkbox>
        </div>
        <div className={styles.columns_container_tree}>
          {/* <Tree checkable onCheck={onCheck} checkedKeys={state.selectedKeys} treeData={columns} /> */}
          <CheckboxGroup options={plainOptions} value={state.selectedKeys} onChange={onCheck} />
        </div>
        <div className={styles.driver} />
        <div className={styles.columns_container_footer}>
          <Button size={'small'} className={styles.btn} onClick={onCancel} loading={state.loading}>
            取消
          </Button>
          <Button
            size={'small'}
            type={'primary'}
            className={styles.btn}
            onClick={onSuccess}
            loading={state.loading}
          >
            确认
          </Button>
        </div>
      </div>
    );
  };
  const columns = [
    {
      code: 'stationName',
      name: '场站',
      width: 110,
      align: 'center',
      render(v: any) {
        return v || '-';
      },
    },
    {
      code: 'powerPurchaserName',
      name: '购电方',
      width: 80,
      align: 'center',
      render(v: any) {
        return v || '-';
      },
    },
    {
      code: 'userType',
      name: '用户类型',
      width: 92,
      align: 'center',
      render(v: any) {
        return USER_TYPE_DIC.filter((i) => i.value === v)?.[0]?.label || '-';
      },
    },
    {
      code: 'sellerPurchaserName',
      name: '售电方',
      width: 244,
      align: 'center',
      render(v: any) {
        return v || '-';
      },
    },
    {
      code: 'tradeSequenceName',
      name: '交易序列',
      width: 219,
      align: 'center',
      render(v: any) {
        return v || '-';
      },
    },
    {
      code: 'contractName',
      name: '合同名称',
      width: 244,
      align: 'center',
      render(v: any, record: any) {
        return (
          <div className={styles.title}>
            <Tooltip placement="topLeft" title={v}>
              <div className={styles.text}>{v || '-'}</div>
            </Tooltip>
            {/*{v ? (*/}
            {/*    <div*/}
            {/*        className={styles.titleLogo}*/}
            {/*        onClick={() => showContratCharts && showContratCharts(record)}*/}
            {/*    >*/}
            {/*        <FileSearchOutlined className={styles.logo}/>*/}
            {/*    </div>*/}
            {/*) : null}*/}
          </div>
        );
      },
    },
    {
      code: 'contractId',
      name: '合同编号',
      width: 112,
      align: 'center',
      render(v: any) {
        return (
          <div className={styles.title}>
            <Tooltip placement="topLeft" title={v}>
              <div className={styles.overflow}>{v || '-'}</div>
            </Tooltip>
          </div>
        );
      },
    },
    {
      code: 'tag',
      name: (
        <div>
          时段
          <Dropdown
            overlay={renderColumns}
            onVisibleChange={() => columnsVisibleChange(true)}
            placement="bottomLeft"
            trigger={['click']}
            visible={state.open}
          >
            <FilterOutlined
              style={{ fontSize: 14, cursor: 'pointer', color: '#18A0FB', paddingLeft: 5 }}
            />
          </Dropdown>
        </div>
      ),
      width: 74,
      align: 'center',
      render(v: any) {
        return (
          <div className={`${styles.timeFontStyle}`} style={{ color: totalColorDic[v] }}>
            {v ?? '-'}
          </div>
        );
      },
    },
    {
      code: 'contractPrice',
      name: '电价(元/MWh)',
      width: 111,
      align: 'center',
      render(v: any, record: any) {
        const text = ToFixed(v, 2);
        return text ?? '-';
      },
    },
    {
      code: 'contractQuantity',
      name: '电量(MWh)',
      width: 93,
      align: 'center',
      render(v: any) {
        const text = ToFixed(v, 3);
        return text ?? '-';
      },
    },
    {
      code: 'powerSourceType',
      name: '电源类型',
      width: 80,
      align: 'center',
    },
    {
      code: 'month',
      name: '月份',
      width: 76,
      align: 'center',
      render(v: any) {
        return v ? moment(v).format('YYYYMM') : '-';
      },
    },
    {
      code: 'contractSource',
      name: '来源',
      width: 80,
      align: 'center',
      render(v: string) {
        const data = v ? contractSourceOptions.find((item) => item.value === v) : {};
        return data?.label || '-';
      },
    },
    {
      code: 'operation',
      name: '操作',
      width: 176,
      align: 'center',
      lock: true,
      render(v: any, record: any) {
        return record.father ? (
          '-'
        ) : (
          <div className={styles.options}>
            {operationList.map((item: any) => (
              <div
                key={item.value}
                className={`${
                  (item.value === IOperationType.EDIT || item.value === IOperationType.DETELE) &&
                  (record?.contractSource === IContractSourceType.TRADING_CENTER ||
                    record?.contractSource === IContractSourceType.TRADING_CENTER_NOMAL ||
                    record?.contractSource === IContractSourceType.TRADING_CENTER_VIRTUAL)
                    ? styles.disableItem
                    : styles.item
                }`}
                onClick={() => onOperation(item, record)}
              >
                {item.label}
              </div>
            ))}
          </div>
        );
      },
    },
  ];

  // 操作
  const onOperation = async (item: IOptionType, record: any) => {
    if (item.value === IOperationType.DETAIL) {
      onDetail?.(record);
    } else if (
      item.value === IOperationType.EDIT &&
      record?.contractSource === IContractSourceType.USER_UPLOAD
    ) {
      const resoult = havePermissions('pendingRemoveButtonV2', buttonPermissions);
      if (resoult) {
        onEdit?.(record);
      }
    } else if (
      item.value === IOperationType.DETELE &&
      record?.contractSource === IContractSourceType.USER_UPLOAD
    ) {
      const resoult = havePermissions('pendingRemoveButtonV2', buttonPermissions);
      if (resoult) {
        onDetele?.(record);
      }
    } else if (item.value === IOperationType.EXPORT) {
      const result = havePermissions('ContractManagementQuantityPriceExport', buttonPermissions);
      if (!result) return;
      PLoading.show('正在导出...');
      const res = await exportXinjiangContract({
        contractId: record.contractId,
        contractSource: record.contractSource,
        date: record.date,
        tag: record.tag,
        stationId: record.stationId,
        id: record.id,
      });
      PLoading.dismiss();
      if (res.file) {
        const url: string = window.URL.createObjectURL(res.file);
        const link: any = document.createElement('a');
        link.download = `${record.contractName}.xlsx`;
        link.href = url;
        link.click();
        link.remove();
      } else {
        message.info('导出失败！');
      }
    }
  };

  /** render */
  const pipeline = useTablePipeline({
    components: { Checkbox },
  })
    .input({ dataSource: state.data, columns: columns as any })
    .primaryKey('idx')
    .use(
      features.treeMode({
        clickArea: 'cell',
      }),
    )
    .use(
      features.treeSelect({
        tree: state.data,
        value: selectedRowKeys,
        highlightRowWhenSelected: true,
        checkedStrategy: 'all',
        checkboxPlacement: 'start',
        checkboxColumn: { lock: true },
        clickArea: 'cell',
        onChange: (nextValue: string[]) => {
          setSelectedRowKeys && setSelectedRowKeys(nextValue);
        },
      }),
    )
    .appendRowPropsGetter((_row): any => {
      const color = '#222629';
      const otherColor = '#21323E';
      return {
        style: {
          '--bgcolor': visible && contractId === _row?.contractId ? otherColor : color,
          '--hover-bgcolor': visible && contractId === _row?.contractId ? otherColor : color,
          '--highlight-bgcolor': visible && contractId === _row?.contractId ? otherColor : color,
        },
      };
    });
  return (
    <>
      <div className={styles.total}>
        {totalData.map((i: any, index: number) => (
          <div style={index !== 0 ? { marginLeft: 80 } : {}} key={index}>
            <div className={styles.head}>
              <div className={styles.box} style={{ background: totalColorDic[i.tag] }} />
              {i.tag + '时段'}
            </div>
            <div className={styles.data}>
              <div>
                电价：<span>{i.electricityPrice}</span> 元/MWh
              </div>
              <div className={styles.dataRight}>
                电量：<span>{i.powerConsumption}</span> MWh
              </div>
            </div>
          </div>
        ))}
      </div>
      <div className={styles.content}>
        <TjTable useVirtual="auto" defaultColumnWidth={90} {...pipeline.getProps()} />
      </div>
    </>
  );
};
export default XJList;
